import kit from "./kit.js" ;

function Qiniu( tokenUrl ){
	this.tokenUrl = tokenUrl || "/api/qiniu/getToken" ;
	this.token = "" ;
	this.fielPath = "" ;
	this.notShowProgress = false ;
}

Qiniu.prototype = {
	
	upload:function( fielPath , callback , noShowProgress){
		this.filePath = fielPath ;
		this.notShowProgress = noShowProgress ;
		this.success = callback || function(){} ;
		kit.get( this.tokenUrl ,{} , res => {
			this.token = res.token ;
			this.domain = res.domain ;
			this.uploadFile();
		});
	},
	
	guid : function () {
	    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
	        var r = Math.random() * 16 | 0,
	            v = c == 'x' ? r : (r & 0x3 | 0x8);
	        return v.toString(16);
	    });
	},
	
	uploadFile:function(){
		const that = this;
		var uploadTask = uni.uploadFile({
			url: "https://upload.qiniup.com" ,
			filePath: this.filePath ,
			name: 'file',
			formData: {
				token : this.token ,
				key : this.guid()
			},
			success :(res) => {
				uni.hideLoading();
				var data = JSON.parse(res.data);
				this.success(this.getImgUrl(data.key));
			},
			fail(err) {
				uni.hideLoading();
				console.log(err)
			}
		});
		
		uploadTask.onProgressUpdate((res) => {
			if (!this.notShowProgress) {
				uni.showLoading({
					title: res.progress + "%"
				});
			}
			if(res.progress >= 100){
				uni.hideLoading();
			}
		});
	},
	
	getImgUrl :function(key){
		return this.domain + key;
	}
};

module.exports = {
	Qiniu
};